package com.stx.jeepay.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.stx.jeepay.core.dao.SysUserDao;
import com.stx.jeepay.core.entity.SysUserAuthEntity;
import com.stx.jeepay.core.entity.SysUserEntity;
import com.stx.jeepay.core.entity.SysUserRoleRelaEntity;
import com.stx.jeepay.core.enums.CS;
import com.stx.jeepay.core.expection.BizException;
import com.stx.jeepay.core.service.SysUserAuthService;
import com.stx.jeepay.core.service.SysUserRoleRelaService;
import com.stx.jeepay.core.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {

    @Autowired
    private SysUserAuthService sysUserAuthService;

    @Autowired
    private SysUserRoleRelaService sysUserRoleRelaService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addSysUser(SysUserEntity sysUser, String sysType) {
        //判断获取到选择的角色集合
//        String roleIdListStr = sysUser.extv().getString("roleIdListStr");
//        if(StringKit.isEmpty(roleIdListStr)) throw new BizException("请选择角色信息！");
//
//        List<String> roleIdList = JSONArray.parseArray(roleIdListStr, String.class);
//        if(roleIdList.isEmpty()) throw new BizException("请选择角色信息！");

        // 判断数据来源
        if (StringUtils.isEmpty(sysUser.getLoginUsername())) {
            throw new BizException("登录用户名不能为空！");
        }
        if (StringUtils.isEmpty(sysUser.getRealname())) {
            throw new BizException("姓名不能为空！");
        }
        if (StringUtils.isEmpty(sysUser.getTelphone())) {
            throw new BizException("手机号不能为空！");
        }
        if (sysUser.getSex() == null) {
            throw new BizException("性别不能为空！");
        }

        //登录用户名不可重复
        if (count(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getSysType, sysType).eq(SysUserEntity::getLoginUsername, sysUser.getLoginUsername())) > 0) {
            throw new BizException("登录用户名已存在！");
        }
        //手机号不可重复
        if (count(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getSysUserId, sysType).eq(SysUserEntity::getTelphone, sysUser.getTelphone())) > 0) {
            throw new BizException("手机号已存在");
        }
        //员工号不可重复
        if (count(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getSysType, sysType).eq(SysUserEntity::getUserNo, sysUser.getUserNo())) > 0) {
            throw new BizException("员工号已存在");
        }

        //女  默认头像
        if (sysUser.getSex() != null && CS.SEX_FEMALE == sysUser.getSex()) {
            sysUser.setAvatarUrl("https://jeequan.oss-cn-beijing.aliyuncs.com/jeepay/img/defava_f.png");
        } else {
            sysUser.setAvatarUrl("https://jeequan.oss-cn-beijing.aliyuncs.com/jeepay/img/defava_m.png");
        }

        //1. 插入用户主表
        sysUser.setSysType(sysType);
        save(sysUser);

        Long sysUserId = sysUser.getSysUserId();
        //添加到 user_auth表
        String authPwd = CS.DEFAULT_PWD;

        sysUserAuthService.addUserAuthDefault(sysUserId, sysUser.getLoginUsername(), sysUser.getTelphone(), authPwd, sysType);

        //3. 添加用户角色信息
        //saveUserRole(sysUser.getSysUserId(), new ArrayList<>());
    }

    /**
     * 获取到商户的超管用户ID
     *
     * @param mchNo
     * @return
     */
    @Override
    public Long findMchAdminUserId(String mchNo) {
        return getOne(new LambdaQueryWrapper<SysUserEntity>()
                .select(SysUserEntity::getSysUserId)
                .eq(SysUserEntity::getBelongInfoId, mchNo)
                .eq(SysUserEntity::getSysType, CS.SYS_TYPE.MCH)
                .eq(SysUserEntity::getIsAdmin, CS.YES)).getSysUserId();

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateSysUser(SysUserEntity sysUser) {
        Long sysUserId = sysUser.getSysUserId();
        SysUserEntity dbRecord = getById(sysUserId);
        if (dbRecord == null) {
            throw new BizException("该用户不存在");
        }

        //修改了手机号， 需要修改auth表信息
        if (!dbRecord.getTelphone().equals(sysUser.getTelphone())) {
            if (count(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getSysType, dbRecord.getSysType()).eq(SysUserEntity::getTelphone, sysUser.getTelphone())) > 0) {
                throw new BizException("该手机号已关联其他用户！");
            }
            sysUserAuthService.resetAuthInfo(sysUserId, null, sysUser.getTelphone(), null, dbRecord.getSysType());
        }

        //修改了手机号， 需要修改auth表信息
        if (!dbRecord.getLoginUsername().equals(sysUser.getLoginUsername())) {
            if (count(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getSysType, dbRecord.getSysType()).eq(SysUserEntity::getLoginUsername, sysUser.getLoginUsername())) > 0) {
                throw new BizException("该登录用户名已关联其他用户！");
            }
            sysUserAuthService.resetAuthInfo(sysUserId, sysUser.getLoginUsername(), null, null, dbRecord.getSysType());
        }
        baseMapper.updateById(sysUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeUser(SysUserEntity sysUser, String sysType) {
        // 1.删除用户登录信息
        sysUserAuthService.remove(new LambdaQueryWrapper<SysUserAuthEntity>()
                .eq(SysUserAuthEntity::getSysType, sysType)
                .in(SysUserAuthEntity::getUserId, sysUser.getSysUserId()));
        // 2.删除用户角色信息
        sysUserRoleRelaService.removeById(sysUser.getSysUserId());
        // 删除用户信息
        removeById(sysUser.getSysUserId());
    }

    /**
     * 分配用户角色
     **/
    @Override
    public void saveUserRole(Long userId, List<String> roleIdList) {
        //删除用户之前的 角色信息
        sysUserRoleRelaService.remove(new LambdaQueryWrapper<SysUserRoleRelaEntity>().eq(SysUserRoleRelaEntity::getUserId, userId));
        for (String roleId : roleIdList) {
            SysUserRoleRelaEntity addRecord = new SysUserRoleRelaEntity();
            addRecord.setUserId(userId);
            addRecord.setRoleId(roleId);
            sysUserRoleRelaService.save(addRecord);
        }
    }
}